package com.jielihaofeng.site.article.controller;

import com.jielihaofeng.site.article.convert.ArticleConvert;
import com.jielihaofeng.site.article.entity.ArticleEntity;
import com.jielihaofeng.site.article.query.ArticleQuery;
import com.jielihaofeng.site.article.service.ArticleService;
import com.jielihaofeng.site.article.vo.ArticleVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import com.jielihaofeng.framework.common.page.PageResult;
import com.jielihaofeng.framework.common.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 个人网站-文章管理
 *
 * @author 借力好风 949394048@qq.com
 * @since 1.0.0 2022-07-21
 */
@RestController
@RequestMapping("site/article")
@Tag(name = "个人网站-文章管理")
@AllArgsConstructor
public class ArticleController {
    private final ArticleService articleService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @PreAuthorize("hasAuthority('site:article:page')")
    public Result<PageResult<ArticleVO>> page(@Valid ArticleQuery query) {
        PageResult<ArticleVO> page = articleService.page(query);

        return Result.ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @PreAuthorize("hasAuthority('site:article:info')")
    public Result<ArticleVO> get(@PathVariable("id") Long id) {
        ArticleEntity entity = articleService.getById(id);

        return Result.ok(ArticleConvert.INSTANCE.convert(entity));
    }

    @PostMapping
    @Operation(summary = "保存")
    @PreAuthorize("hasAuthority('site:article:save')")
    public Result<Long> save(@RequestBody ArticleVO vo) {
        Long id = articleService.save(vo);

        return Result.ok(id);
    }

    @PutMapping
    @Operation(summary = "修改")
    @PreAuthorize("hasAuthority('site:article:update')")
    public Result<Long> update(@RequestBody @Valid ArticleVO vo) {
        Long id = articleService.update(vo);

        return Result.ok(id);
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @PreAuthorize("hasAuthority('site:article:delete')")
    public Result<String> delete(@RequestBody List<Long> idList) {
        articleService.delete(idList);

        return Result.ok();
    }
}